/**
 * @file
 * @auth jinguangguo
 * @date 2016/10/17
 */

import gulp from 'gulp';
import sequence from 'gulp-sequence';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import autoresponse from 'autoresponse';
import request from 'superagent';

import util from './util';

let browserSync = require('browser-sync').create();

global.browserSync = browserSync;

import webpackConfig from '../webpack.config.babel';

gulp.task('reload', sequence(
    ['html:server', 'js:server', 'scss:server', 'img:server', 'icon:server', 'third:server','favicon:server']
));

function loadingCompiler() {
    if (!webpackConfig.plugins) {
        webpackConfig.plugins = [];
    }
    webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

    webpackConfig.devtool = 'source-map';

    const webpackClient = 'webpack-hot-middleware/client?reload=true';

    for (let key in webpackConfig.entry) {
        webpackConfig.entry[key].unshift(webpackClient);
    }

    return webpack(webpackConfig);
}

gulp.task('server', ['reload'], function() {

    let compiler = loadingCompiler();

    browserSync.init({
        server: "./dev",
        port: 8000,
        open: false,
        middleware: [
            webpackDevMiddleware(compiler, {
                hot: true,
                // display no info to console (only warnings and errors)
                noInfo: true,
                // display nothing to the console
                quiet: true,
                historyApiFallback: true,
                stats: {
                    colors: true
                },
                watchOptions: {
                    aggregateTimeout: 300,
                    poll: 1000
                },
                publicPath: webpackConfig.output.publicPath
            }),
            webpackHotMiddleware(compiler),
            getAutoResponse()
        ],
        ui: {
            port: 8001,
            weinre: {
                port: 8002
            }
        }
    });

    function getAutoResponse() {
        return autoresponse({
            responseDir: './mock',
            logLevel: 'info',
            post: true,
            get: {
                match: function (reqPathName) { // mock all `/xx/xx` path
                    return !/\.\w+(\?.*)?$/.test(reqPathName);
                }
            }
        });
    }

});

// 测试环境调试
gulp.task('server:remote', ['reload'], function() {

    let compiler = loadingCompiler();

    const TEST_HOST = 'http://gdae2.dev.gpdax.com';
    // const TEST_HOST = 'http://www.quickdax.com';

    browserSync.init({
        server: "./dev",
        port: 9000,
        open: false,
        middleware: [
            webpackDevMiddleware(compiler, {
                hot: true,
                // display no info to console (only warnings and errors)
                noInfo: false,
                // display nothing to the console
                quiet: true,
                // switch into lazy mode
                // that means no watching, but recompilation on every request
                lazy: false,
                historyApiFallback: true,
                stats: {
                    colors: true
                },
                watchOptions: {
                    aggregateTimeout: 300,
                    poll: 1000
                },
                publicPath: webpackConfig.output.publicPath
            }),
            webpackHotMiddleware(compiler),
            function (req, res, next) {
                const REG_STATIC = /\w\.(html|js|css|scss|png|gif|jpg|ttf|eot|svg|woff|ico)/gi; //判断是否是资源文件
                if (REG_STATIC.test(req.originalUrl)) {
                    next();
                } else {
                    res.setHeader("Content-Type", "application/json;charset=UTF-8");
                    // global.logger.warn('remote request begin: ' + req.originalUrl);
                    let dataArr = [];
                    req.on("data", function (data) {//接收参数
                        dataArr.push(data);
                    });
                    req.on("end", function () {
                        let data = Buffer.concat(dataArr).toString();
                        // let host= 'http://exchange.treespaper.com';
                        // let host = 'http://www.dev.gpdax.com';

                        // let host = 'http://gdae2.dev.gpdax.com';  // 测试接口

                        // let host = 'https://www.ourdax.com';  // 测试接口

                        let host = TEST_HOST;   //haotian
                        if (req.originalUrl.indexOf('exchangeApi') >= 0) {
                            host = TEST_HOST;
                            // host = 'http://10.23.0.35:8580';    // haotian
                            // host = 'http://10.23.2.152:8580';//shengtao
                            // host = 'http://10.23.0.132:8580';//liwei
                        }

                        global.logger.warn('request get is begin : ' + host + req.originalUrl);

                        // 小春
                        // let host = 'http://10.23.2.143:8580';
                        // if (req.originalUrl.indexOf('c2cApi') >= 0) {
                        //     host = 'http://10.23.2.143:8581';
                        // }

                        // shengtao
                        // let host = 'http://10.23.2.152:8580';
                        // if (req.originalUrl.indexOf('c2cApi') >= 0) {
                        //     host = 'http://10.23.2.152:8581';
                        // }

                        // haotian
                        // let host = 'http://10.23.0.35:8580';
                        // if (req.originalUrl.indexOf('c2cApi') >= 0) {
                        //     host = 'http://10.23.0.35:8581';
                        // }

                        //liwei
                        // let host = 'http://10.23.0.132:8580';
                        // if (req.originalUrl.indexOf('c2cApi') >= 0) {
                        //     host = 'http://10.23.0.132:8581';
                        // }


                        let params = {};
                        try {
                            params = JSON.parse(data);
                        } catch (err) {
                            // throw err;
                            params = data;
                        }

                        // global.logger.info('req.headers:' + JSON.stringify(req.headers));

                        if (req.method.toUpperCase() == 'GET') {
                            if (req.originalUrl.indexOf('exchangeApi/user/login') >= 0) {
                                global.logger.warn('The login begin ...');
                                request
                                    .get(host + req.originalUrl)
                                    .send(params)
                                    .set('Accept', 'application/json')
                                    .set('accept-language', req.headers['accept-language'])
                                    .set('Authorization', req.headers['authorization'] || '')
                                    .set('Cookie', req.headers.cookie || '')
                                    .end((err, resInner) => {
                                        global.logger.info('The set-cookie is: ' + JSON.stringify(resInner.header['set-cookie']));

                                        // 登录失败或者近期内使用同一个session
                                        if (!resInner.header['set-cookie']) {
                                            res.end(resInner.text);
                                        } else {
                                            let cookieFromServer = resInner.header['set-cookie'][0];

                                            let sessionValue = cookieFromServer.split(';')[0].split('=')[1];
                                            global.logger.info('Your current session is :' + sessionValue);

                                            res.setHeader('set-cookie', cookieFromServer);
                                            res.end(resInner.text);
                                        }
                                    });
                            } else if (req.originalUrl.indexOf('exchangeApi/captchar/code') >= 0) {
                                global.logger.warn('The img code begin ...');
                                request
                                    .get(host + req.originalUrl)
                                    .send(params)
                                    .set('Accept', 'image/*')
                                    .set('Cookie', req.headers.cookie || '')
                                    .set('Authorization', req.headers['authorization'] || '')
                                    .pipe(res);
                                // } else if (req.originalUrl.indexOf('trade/info') >= 0 || req.originalUrl.indexOf('trade/trade') >= 0
                                //     || req.originalUrl.indexOf('trade/detail') >= 0) {
                                //     request
                                //         .get(TEST_HOST + req.originalUrl)
                                //         .send(params)
                                //         .set('Accept', 'application/json')
                                //         .set('accept-language', req.headers['accept-language'])
                                //         .set('Cookie', req.headers.cookie || '')
                                //         .set('Authorization', req.headers['authorization'] || '')
                                //         .pipe(res);
                            } else {
                                request
                                    .get(host + req.originalUrl)
                                    .send(params)
                                    .set('Accept', 'application/json')
                                    .set('accept-language', req.headers['accept-language'])
                                    .set('Cookie', req.headers.cookie || '')
                                    .set('Authorization', req.headers['authorization'] || '')
                                    .pipe(res);
                            }
                        } else if (req.method.toUpperCase() == 'POST') {
                            if (req.originalUrl.indexOf('exchangeApi/login/quickLoginByEmail') >= 0
                                || req.originalUrl.indexOf('exchangeApi/user/email-login') >= 0) {
                                request
                                    .post(host + req.originalUrl)
                                    .send(params)
                                    .set('Accept', 'application/json')
                                    .set('accept-language', req.headers['accept-language'])
                                    .set('Authorization', req.headers['authorization'] || '')
                                    .set('Cookie', req.headers.cookie || '')
                                    .end((err, resInner) => {
                                        console.log(JSON.stringify(resInner));
                                        global.logger.info('The set-cookie is: ' + JSON.stringify(resInner.header['set-cookie']));

                                        // 登录失败或者近期内使用同一个session
                                        if (!resInner.header['set-cookie']) {
                                            res.end(resInner.text);
                                            // res.end(JSON.stringify(resInner));
                                        } else {
                                            let cookieFromServer = resInner.header['set-cookie'][0];

                                            let sessionValue = cookieFromServer.split(';')[0].split('=')[1];
                                            global.logger.info('Your current session is :' + sessionValue);

                                            res.setHeader('set-cookie', cookieFromServer);
                                            res.end(resInner.text);
                                        }
                                    });
                            } else {
                                request
                                    .post(host + req.originalUrl)
                                    .send(params)
                                    .set('Accept', 'application/json')
                                    .set('accept-language', req.headers['accept-language'])
                                    .set('Authorization', req.headers['authorization'] || '')
                                    .set('Cookie', req.headers.cookie || '')
                                    .pipe(res);
                            }
                        } else if (req.method.toUpperCase() == 'DELETE') {
                            console.log('DELTE BEGIN ...');
                            request
                                .delete(host + req.originalUrl)
                                .send(params)
                                .set('Accept', 'application/json')
                                .set('accept-language', req.headers['accept-language'])
                                .set('Authorization', req.headers['authorization'] || '')
                                .set('Cookie', req.headers.cookie || '')
                                .pipe(res);
                        }
                    })
                }
            }
        ],
        ui: {
            port: 9001,
            weinre: {
                port: 9002
            }
        }
    });

});

